/**
 * 
 */
package com.myGisChannel.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.measure.unit.Dimension.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.hibernate.metamodel.domain.Superclass;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractWizardFormController;

import com.myGis.entities.Layer;
import com.myGis.entities.Project;
import com.myGis.entities.SimpleField;
import com.myGis.entities.User;
import com.myGis.services.IMyGisServices;
import com.myGis.services.MyGisServer;
import com.myGis.util.Util;
import com.myGisChannel.command.LayerCreateCommand;

/**
 * @author Administrador
 *
 */
@SuppressWarnings("deprecation")
public class LayerCreateController extends AbstractWizardFormController{
	
	private static final String CUSTOM_LAYER="CO"; 
	private static String path = "/resources/img/markers";
	private int PAGE_0 = 0;
	private int PAGE_1 = 1;

	protected Map referenceData(HttpServletRequest request, Object command,	Errors errors, int page){
		LayerCreateCommand lcc = (LayerCreateCommand)command;
		Map referenceData = new HashMap();
		if(request.getParameter("idProject")!=null)
			lcc.setIdProject(request.getParameter("idProject"));
		
		if(PAGE_1 == page){
			referenceData.put("markerSelected", lcc.getMarketSelected());

		}
		// Pongo esto aca asi en el jsp puede mostrar el nombre del proyecto y esa cosas.
		User user = (User) request.getSession(true).getAttribute("user");
		List<Project> projects = user.getProjects();

		Project projectSelected= null;
		for (Project project : projects) {
			if(lcc.getIdProject().equals(project.getProjectId().toString())){
				projectSelected=project;
				break;
			}
		}

		
		Layer layerSelected = null;
		if(null != request.getParameter("idLayer")){
			String idLayerSelected = request.getParameter("idLayer"); 
			List<Layer> layers = projectSelected.getLayers();
			for(Layer layer:layers){
				if(idLayerSelected.equals(layer.getLayerId().toString())){
					layerSelected = layer;
					break;
				}
			}
			lcc.setEdit(true);
		}

		//Map referenceData = new HashMap();
		if(null != layerSelected){//Si entro a este if es que estoy en busca de la edicion de un capa custom por lo que tengo que prersetear los campos necesarios.
			lcc.setLayerName(layerSelected.getName());
			lcc.setTypeLayer(layerSelected.getLayerType());//Esto hay que arreglarlo!!!. ya que no este bien en el jsp para que quede automatizado.
			lcc.setDinamicInputNameHidden(layerSelected.getLayerForm());
		}
		
		Map<String,String> layerType = new LinkedHashMap<String,String>();
		layerType.put("CO", "Custom");
		layerType.put("BA", "Shape File");
		referenceData.put("layerType", layerType);
		
		lcc.setSelectedProject(projectSelected);

		//Seteo el conjunto de marcadores que podra seleccionar la capa.
		HashMap<String ,Object> data = new HashMap<String, Object>();
		List markers = getMarkers();
		referenceData.put("markers", markers);
		
		return referenceData;
		
	}
	
	
	
	protected void postProcessPage(javax.servlet.http.HttpServletRequest request, java.lang.Object command, org.springframework.validation.Errors errors, int page){
		LayerCreateCommand lcc = (LayerCreateCommand)command;
		
		if(PAGE_0 == page){
			return;
		}else if(PAGE_1 == page){
			return;
		}
		
		/*
		User user = (User) request.getSession(true).getAttribute("user");
		
		Layer newLayer = new Layer();
		newLayer.setName(lcc.getLayerName());

		
		IMyGisServices mgs = MyGisServer.getInstance();
		//[{"nombre_campo":"Nombre","tipo_campo":"text"},{"nombre_campo":"Apellido","tipo_campo":"text"}]
		if(CUSTOM_LAYER.equals(lcc.getTypeLayer())){
			newLayer.setLayerType("CO");
			String dinamicForm = lcc.getDinamicInputNameHidden();
			newLayer.setLayerForm(dinamicForm);
			newLayer.setMarker(lcc.getMarketSelected().replace(".png", ""));
			JSONArray items = new JSONArray(dinamicForm);
			
			for (int i = 0; i < items.length(); i++) {
				JSONObject object = items.getJSONObject(i);
				   String nombreInput = object.getString("nombre_campo");
				   String tipoInput = object.getString("tipo_campo");
				   SimpleField sfe = new SimpleField();
					sfe.setLayer(newLayer);
					sfe.setName(nombreInput);
					sfe.setType(tipoInput);
					newLayer.getSimpleFields().add(sfe);
			}
			lcc.setIdProject(new Long(lcc.getSelectedProject().getProjectId()).toString());
			mgs.saveLayerCustom(lcc.getSelectedProject(), newLayer);
		}else{
			newLayer.setLayerType("BA");
			CommonsMultipartFile shape = (CommonsMultipartFile) lcc.getShape();
			CommonsMultipartFile shx = (CommonsMultipartFile) lcc.getShx();
			CommonsMultipartFile dbf = (CommonsMultipartFile) lcc.getDbf();
			CommonsMultipartFile prj = (CommonsMultipartFile) lcc.getPrj();
			
			String pathShape = ((DiskFileItem)shape.getFileItem()).getStoreLocation().getParent();
			String pathShx = ((DiskFileItem)shx.getFileItem()).getStoreLocation().getParent();
			String pathDbf = ((DiskFileItem)dbf.getFileItem()).getStoreLocation().getParent();
			
			File localFileShape = new File(pathShape+"\\"+shape.getOriginalFilename());
			File localFileShx = new File(pathShx+"\\"+shx.getOriginalFilename());
			File localFileDbf = new File(pathDbf+"\\"+dbf.getOriginalFilename());
			//File localFilePrj = new File(pathPrj+"\\"+prj.getOriginalFilename());
			FileOutputStream osShape = null;
			FileOutputStream osShx = null;
			FileOutputStream osDbf = null;
			//FileOutputStream osPrj = null;
			try {
				osShape = new FileOutputStream(localFileShape);
				osShape.write(shape.getBytes());
				
				osShx = new FileOutputStream(localFileShx);
				osShx.write(shx.getBytes());
				
				osDbf = new FileOutputStream(localFileDbf);
				osDbf.write(dbf.getBytes());
				
				//osPrj = new FileOutputStream(localFilePrj);
				//osPrj.write(prj.getBytes());
				
				mgs.saveLayerBasic(localFileShape,lcc.getSelectedProject(),newLayer);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		*/
	}
	
	@Override
	protected ModelAndView processFinish(HttpServletRequest request,
			HttpServletResponse arg1, Object command, BindException arg3)
			throws Exception {
		ModelAndView mav = new ModelAndView("layersPages/layerCreateResult");
		
		LayerCreateCommand lcc = (LayerCreateCommand)command;
		
		Layer newLayer = new Layer();
		newLayer.setName(lcc.getLayerName());
		User user = (User) request.getSession(true).getAttribute("user");
		
		IMyGisServices mgs = MyGisServer.getInstance();
		//[{"nombre_campo":"Nombre","tipo_campo":"text"},{"nombre_campo":"Apellido","tipo_campo":"text"}]
		if(CUSTOM_LAYER.equals(lcc.getTypeLayer())){
			newLayer.setLayerType("CO");
			String dinamicForm = lcc.getDinamicInputNameHidden();
			newLayer.setLayerForm(dinamicForm);
			newLayer.setMarker(lcc.getMarketSelected().replace(".png", ""));
			JSONArray items = new JSONArray(dinamicForm);
			
			for (int i = 0; i < items.length(); i++) {
				JSONObject object = items.getJSONObject(i);
				   String nombreInput = object.getString("nombre_campo");
				   String tipoInput = object.getString("tipo_campo");
				   SimpleField sfe = new SimpleField();
					sfe.setLayer(newLayer);
					sfe.setName(nombreInput);
					sfe.setType(tipoInput);
					newLayer.getSimpleFields().add(sfe);
			}
			lcc.setIdProject(new Long(lcc.getSelectedProject().getProjectId()).toString());
			mgs.saveLayerCustom(lcc.getSelectedProject(), newLayer);
			mav.addObject("projectName", lcc.getSelectedProject().getName());
		}else{
			newLayer.setLayerType("BA");
			CommonsMultipartFile shape = (CommonsMultipartFile) lcc.getShape();
			CommonsMultipartFile shx = (CommonsMultipartFile) lcc.getShx();
			CommonsMultipartFile dbf = (CommonsMultipartFile) lcc.getDbf();
			CommonsMultipartFile prj = (CommonsMultipartFile) lcc.getPrj();
			
			String pathShape = ((DiskFileItem)shape.getFileItem()).getStoreLocation().getParent();
			String pathShx = ((DiskFileItem)shx.getFileItem()).getStoreLocation().getParent();
			String pathDbf = ((DiskFileItem)dbf.getFileItem()).getStoreLocation().getParent();
			
			File localFileShape = new File(pathShape+"\\"+shape.getOriginalFilename());
			File localFileShx = new File(pathShx+"\\"+shx.getOriginalFilename());
			File localFileDbf = new File(pathDbf+"\\"+dbf.getOriginalFilename());
			//File localFilePrj = new File(pathPrj+"\\"+prj.getOriginalFilename());
			FileOutputStream osShape = null;
			FileOutputStream osShx = null;
			FileOutputStream osDbf = null;
			//FileOutputStream osPrj = null;
			try {
				osShape = new FileOutputStream(localFileShape);
				osShape.write(shape.getBytes());
				
				osShx = new FileOutputStream(localFileShx);
				osShx.write(shx.getBytes());
				
				osDbf = new FileOutputStream(localFileDbf);
				osDbf.write(dbf.getBytes());
				
				//osPrj = new FileOutputStream(localFilePrj);
				//osPrj.write(prj.getBytes());
				
				mgs.saveLayerBasic(localFileShape,lcc.getSelectedProject(),newLayer);
				mav.addObject("projectName", lcc.getSelectedProject().getName());
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
		return mav;
	}
	
	private List<String> getMarkers(){
		List<String> markers = new ArrayList<String>();
		markers.add("administration");
		markers.add("aestheticscenter");
		markers.add("aircraft-small");
		markers.add("airplane-sport");
		markers.add("airport");
		markers.add("amphitheater");
		markers.add("anniversary");
		markers.add("apartment");
		markers.add("aquarium");
		markers.add("archery");
		markers.add("atv");
		markers.add("audio");
		markers.add("australianfootball");
		markers.add("bags");
		markers.add("bank");
		markers.add("bankeuro");
		markers.add("bankpound");
		markers.add("bar");
		markers.add("baseball");
		markers.add("basketball");
		markers.add("baskteball2");
		markers.add("bench");
		markers.add("bicycleparking");
		markers.add("billiard");
		markers.add("bobsleigh");
		markers.add("bomb");
		markers.add("bookstore");
		markers.add("bowling");
		markers.add("boxing");
		markers.add("bread");
		markers.add("bullfight");
		markers.add("bungalow");
		markers.add("bus");
		markers.add("butcher");
		markers.add("cablecar");
		markers.add("canoe");
		markers.add("car");
		markers.add("carrental");
		markers.add("carrepair");
		markers.add("carwash");
		markers.add("casino");
		markers.add("cinema");
		markers.add("circus");
		markers.add("climbing");
		markers.add("clothes-female");
		markers.add("clothes-male");
		markers.add("clothes");
		markers.add("clouds");
		markers.add("cloudsun");
		markers.add("club");
		markers.add("cluster");
		markers.add("cluster2");
		markers.add("cluster3");
		markers.add("cluster4");
		markers.add("cluster5");
		markers.add("cocktail");
		markers.add("coffee");
		markers.add("communitycentre");
		markers.add("company");
		markers.add("computer");
		markers.add("concessionaire");
		markers.add("conference");
		markers.add("construction");
		markers.add("convenience");
		markers.add("court");
		markers.add("cricket");
		markers.add("crossingguard");
		markers.add("currencyexchange");
		markers.add("customs");
		markers.add("cycling");
		markers.add("cyclingfeedarea");
		markers.add("cyclingmountain1");
		markers.add("cyclingmountain2");
		markers.add("cyclingmountain3");
		markers.add("cyclingmountain4");
		markers.add("cyclingmountainnotrated");
		markers.add("cyclingsport");
		markers.add("cyclingsprint");
		markers.add("cyclinguncategorized");
		markers.add("dam");
		markers.add("dancinghall");
		markers.add("dates");
		markers.add("daycare");
		markers.add("days-dim");
		markers.add("days-dom");
		markers.add("days-jeu");
		markers.add("days-jue");
		markers.add("days-lun");
		markers.add("days-mar");
		markers.add("days-mer");
		markers.add("days-mie");
		markers.add("days-qua");
		markers.add("days-qui");
		markers.add("days-sab");
		markers.add("days-sam");
		markers.add("days-seg");
		markers.add("days-sex");
		markers.add("days-ter");
		markers.add("days-ven");
		markers.add("days-vie");
		markers.add("dentist");
		markers.add("deptstore");
		markers.add("disability");
		markers.add("disabledparking");
		markers.add("diving");
		markers.add("doctor");
		markers.add("door");
		markers.add("drinkingfountain");
		markers.add("drugs");
		markers.add("elevator");
		markers.add("embassy");
		markers.add("entrance");
		markers.add("escalator-down");
		markers.add("escalator-up");
		markers.add("exit");
		markers.add("expert");
		markers.add("explosion");
		markers.add("factory");
		markers.add("fallingrocks");
		markers.add("family");
		markers.add("fastfood");
		markers.add("festival");
		markers.add("findajob");
		markers.add("findjob");
		markers.add("fire-extinguisher");
		markers.add("fire");
		markers.add("firemen");
		markers.add("fireworks");
		markers.add("firstaid");
		markers.add("fishing");
		markers.add("fishingshop");
		markers.add("fitnesscenter");
		markers.add("flood");
		markers.add("flowers");
		markers.add("followpath");
		markers.add("foodtruck");
		markers.add("friday");
		markers.add("friends");
		markers.add("gazstation");
		markers.add("gifts");
		markers.add("girlfriend");
		markers.add("golf");
		markers.add("gourmet");
		markers.add("grocery");
		markers.add("gun");
		markers.add("gym");
		markers.add("hairsalon");
		markers.add("handball");
		markers.add("hanggliding");
		markers.add("hats");
		markers.add("helicopter");
		markers.add("highway");
		markers.add("hiking");
		markers.add("home");
		markers.add("horseriding");
		markers.add("hospital");
		markers.add("hostel");
		markers.add("hotairballoon");
		markers.add("hotel");
		markers.add("hotel1star");
		markers.add("hotel2stars");
		markers.add("hotel3stars");
		markers.add("hotel4stars");
		markers.add("hotel5stars");
		markers.add("hunting");
		markers.add("icecream");
		markers.add("icehockey");
		markers.add("iceskating");
		markers.add("info");
		markers.add("jewelry");
		markers.add("jogging");
		markers.add("judo");
		markers.add("justice");
		markers.add("karate");
		markers.add("karting");
		markers.add("kayak");
		markers.add("laboratory");
		markers.add("laundromat");
		markers.add("library");
		markers.add("liquor");
		markers.add("lock");
		markers.add("lockerrental");
		markers.add("magicshow");
		markers.add("mainroad");
		markers.add("markest.txt");
		markers.add("massage");
		markers.add("military");
		markers.add("mine");
		markers.add("mobilephonetower");
		markers.add("monday");
		markers.add("motorbike");
		markers.add("motorcycle");
		markers.add("movierental");
		markers.add("museum-archeological");
		markers.add("museum-art");
		markers.add("museum-crafts");
		markers.add("museum-historical");
		markers.add("museum-naval");
		markers.add("museum-science");
		markers.add("museum-war");
		markers.add("museum");
		markers.add("music-classical");
		markers.add("music-hiphop");
		markers.add("music-live");
		markers.add("music-rock");
		markers.add("music");
		markers.add("nanny");
		markers.add("newsagent");
		markers.add("nordicski");
		markers.add("nursery");
		markers.add("observatory");
		markers.add("oilpumpjack");
		markers.add("ophthalmologist");
		markers.add("paint");
		markers.add("parkandride");
		markers.add("parking");
		markers.add("party");
		markers.add("patisserie");
		markers.add("pedestriancrossing");
		markers.add("pens");
		markers.add("perfumery");
		markers.add("personalwatercraft");
		markers.add("pets");
		markers.add("phones");
		markers.add("photo");
		markers.add("photodown");
		markers.add("photodownleft");
		markers.add("photodownright");
		markers.add("photography");
		markers.add("photoleft");
		markers.add("photoright");
		markers.add("photoup");
		markers.add("photoupleft");
		markers.add("photoupright");
		markers.add("pizza");
		markers.add("planecrash");
		markers.add("playground");
		markers.add("poker");
		markers.add("police");
		markers.add("police2");
		markers.add("pool-indoor");
		markers.add("pool");
		markers.add("port");
		markers.add("postal");
		markers.add("powerlinepole");
		markers.add("powerplant");
		markers.add("powersubstation");
		markers.add("prison");
		markers.add("publicart");
		markers.add("racing");
		markers.add("radiation");
		markers.add("rain");
		markers.add("realestate");
		markers.add("recycle");
		markers.add("regroup");
		markers.add("resort");
		markers.add("restaurant-barbecue");
		markers.add("restaurant-buffet");
		markers.add("restaurant-fish");
		markers.add("restaurant-romantic");
		markers.add("restaurant");
		markers.add("restaurantafrican");
		markers.add("restaurantchinese");
		markers.add("restaurantfishchips");
		markers.add("restaurantgourmet");
		markers.add("restaurantgreek");
		markers.add("restaurantindian");
		markers.add("restaurantitalian");
		markers.add("restaurantjapanese");
		markers.add("restaurantkebab");
		markers.add("restaurantkorean");
		markers.add("restaurantmediterranean");
		markers.add("restaurantmexican");
		markers.add("restaurantthai");
		markers.add("restaurantturkish");
		markers.add("revolution");
		markers.add("ropescourse");
		markers.add("rowboat");
		markers.add("rugby");
		markers.add("sailboat-sport");
		markers.add("sailboat");
		markers.add("satursday");
		markers.add("sauna");
		markers.add("school");
		markers.add("schrink");
		markers.add("sciencecenter");
		markers.add("seniorsite");
		markers.add("shoes");
		markers.add("shoppingmall");
		markers.add("shower");
		markers.add("skateboarding");
		markers.add("skiing");
		markers.add("skijump");
		markers.add("skilift");
		markers.add("smokingarea");
		markers.add("sneakers");
		markers.add("snow");
		markers.add("snowboarding");
		markers.add("snowmobiling");
		markers.add("snowshoeing");
		markers.add("soccer");
		markers.add("soccer2");
		markers.add("spaceport");
		markers.add("speedhump");
		markers.add("spelunking");
		markers.add("stadium");
		markers.add("steamtrain");
		markers.add("stop");
		markers.add("stoplight");
		markers.add("strike");
		markers.add("strike1");
		markers.add("subway");
		markers.add("sun");
		markers.add("sunday");
		markers.add("supermarket");
		markers.add("surfing");
		markers.add("suv");
		markers.add("tailor");
		markers.add("tapas");
		markers.add("taxi");
		markers.add("taxiway");
		markers.add("teahouse");
		markers.add("telephone");
		markers.add("tennis");
		markers.add("tennis2");
		markers.add("terrace");
		markers.add("text");
		markers.add("textiles");
		markers.add("theater");
		markers.add("themepark");
		markers.add("thunder");
		markers.add("thursday");
		markers.add("toilets");
		markers.add("tollstation");
		markers.add("tools");
		markers.add("toys");
		markers.add("trafficenforcementcamera");
		markers.add("train");
		markers.add("tram");
		markers.add("trash");
		markers.add("truck");
		markers.add("tuesday");
		markers.add("tunnel");
		markers.add("university");
		markers.add("usfootball");
		markers.add("vespa");
		markers.add("vet");
		markers.add("video");
		markers.add("videogames");
		markers.add("villa");
		markers.add("waitingroom");
		markers.add("waterpark");
		markers.add("waterskiing");
		markers.add("watertower");
		markers.add("wedding");
		markers.add("wednesday");
		markers.add("white1");
		markers.add("white20");
		markers.add("wifi");
		markers.add("windsurfing");
		markers.add("windturbine");
		markers.add("winery");
		markers.add("workoffice");
		markers.add("yoga");
		markers.add("youthhostel");
		markers.add("zipline");
		markers.add("zoo");
		return markers;
	}

}
